package com.cunshe.service;

import com.cunshe.common.DictConsts;
import com.cunshe.dao.UserDao;
import com.cunshe.domain.User;
import com.sunkee.commons.utils.StringUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 登陆用户
 * @author xiao
 */
@Mapper
@Repository
public class UserService {

    @Autowired
    private UserDao userDao;

    /** 新增 */
    @Transactional(rollbackFor = Exception.class)
    public int insert(User record) {
        record.setStatus(DictConsts.STATUS_NORMAL);
        record.setCreatetime(new Date());
        return userDao.insert(record);
    }

    /** 删除 */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        if(id == 1){
            return 0;
        }
        return userDao.delete(id);
    }

    /** 修改 */
    @Transactional(rollbackFor = Exception.class)
    public int update(User record) {
        record.setUpdatetime(new Date());
        return userDao.update(record);
    }

    /** 根据id查询 */
    public User get(Long id) {
        if(id == null) return null;
        return list(User.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    /** 根据loginid查询 */
    public User getUserByLoginid(String loginid) {
        if(StringUtils.isBlank(loginid)) return null;
        return list(User.builder().loginid(loginid).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    /** 查询列表 */
    public List<User> list(User record) {
        return userDao.list(record);
    }

}